package com.yanq.liancar.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.QueryUserBaseMessageBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;



public class SmallCPersonalInformation extends BaseToolbarActivity {
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.headimg)
    CircleImageView headimg;
    @BindView(R.id.et_Nickname)
    TextView etNickname;
    @BindView(R.id.et_name)
    TextView etName;
    @BindView(R.id.et_sex)
    TextView etSex;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_Nickname)
    LinearLayout llNickname;
    @BindView(R.id.ll_name)
    LinearLayout llName;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;
    @BindView(R.id.ll_head_img)
    LinearLayout ll_head_img;
    @BindView(R.id.tv_jianjie1)
    TextView tv_jianjie;

    private Uri resultUri;
    private String where,token;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true, false);
        setContentView(R.layout.activity_personalinformation);
        ButterKnife.bind(this);
        mTvTitle.setText("个人基本信息");
        where=getIntent().getExtras().getString("where");
        if ("MineFragment".equals(where)){
            token=UserBean.getcToken(this);
        }else {
            token=UserBean.getbToken(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initOkGo();
    }

    private void initOkGo() {
        OkGo.<String>post(Config.s + "llc/queryUserBaseMessage")
                .tag(this)
                .params("token",token)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        QueryUserBaseMessageBean bean = gson.fromJson(response.body(), QueryUserBaseMessageBean.class);
                        if (bean.isIsSuccess()) {
                            RequestOptions options=new RequestOptions();
                            options.error(R.mipmap.vip_touxiang);
                            Glide.with(SmallCPersonalInformation.this).load(bean.getData().getHeadPage()).apply(options).into(headimg);
                            etNickname.setText(bean.getData().getNickname());
                            etName.setText(bean.getData().getUsername());
                            etSex.setText(bean.getData().getSex());
                            tv_jianjie.setText(bean.getData().getSign());
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }

                    }
                });
    }

    @OnClick({R.id.ll_Nickname, R.id.ll_name, R.id.ll_sex, R.id.ll_head_img,R.id.rl_jianjie})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_Nickname:
                Bundle bundle=new Bundle();
                bundle.putString("Nickname","Nickname");
                bundle.putString("where",where);
                RxActivityTool.skipActivity(mContext, SmallCEditActivity.class,bundle);
                break;
            case R.id.ll_name:
                Bundle bundl1=new Bundle();
                bundl1.putString("username","username");
                bundl1.putString("where",where);
                RxActivityTool.skipActivity(mContext, SmallCEditActivity.class,bundl1);
                break;
            case R.id.ll_sex:
                Bundle bundl2=new Bundle();
                bundl2.putString("sex","sex");
                bundl2.putString("where",where);
                RxActivityTool.skipActivity(mContext, SmallCEditActivity.class,bundl2);
                break;
            case R.id.ll_head_img:
                RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this);
                dialogChooseImage.show();
                break;
            case R.id.rl_jianjie:
                Bundle bundl3=new Bundle();
                bundl3.putString("sign","sign");
                bundl3.putString("where",where);
                RxActivityTool.skipActivity(mContext, SmallCEditActivity.class,bundl3);
                break;
        }
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {

        Glide.with(this).
                load(uri).
                thumbnail(0.5f).
                into(imageView);


        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }


    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);

                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;
                File file0 = roadImageView(resultUri, headimg);
                initUploadImage(file0);
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    File file = roadImageView(resultUri, headimg);
                    initUploadImage(file);

                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
//        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initUploadImage(File phoneStr) {
        OkGo.<String>post(Config.s + "llc/updateHeadPage")
                .tag(this)
                .params("token", token)
                .params("file", phoneStr)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {

                            initOkGo();
                        }else{
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });

    }
}
